04. Spring Boot MVC Development Introduction

035ND C01 L02 A06 SPRINGBOOT DEVELOPMENT

035ND C01 L02 A07 CREATE CONTROLLER

If you don’t know what Json is, please take a look at here: https://www.w3schools.com/whatis/whatis_json.asp

Instructions

Add a simple controller

Create a controller package under com.example.helloworld.
Create a Java class named HelloController. And make the content like below.

@Controller
public class HelloController {
   private Map<String, Object> result = new HashMap<>();

   @RequestMapping("/hello")
   @ResponseBody
   public Map<String, Object> hello() {
       result.put("name", "Stephen");
       result.put("city", "San Jose");
       return result;
   }
}

If you see any red bulb, click that and select import. Will solve the import issue. Notice that IntelliJ will automatically add the dependency to your pom.xml file. For this example, the spring-boot-web will be added to your dependency list.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Now you can run command below in your IntelliJ Terminal:

mvn spring-boot:run 

Once you see something like “Completed initialization in xxx ms”. Open a browser, and goto
http://localhost:8080/hello
You should see something like “{"city":"San Jose","name":"Stephen"}

035ND C01 L02 A08 CREATE SIMPLE SPRINGBOOT CONTROLLER

Use RestController

035ND C01 L02 A09 REST CONTROLLER

@RestController is a specialized version of controller, which includes @Controller and @ResponseBody. In this example, we are going to use it to update our existing Controller class we created previously.
Steps:

  1. Replace the @Controller with @RestController.

  2. Remove @ResponseBody annotation.

If you have auto imports, the imports will be changed when you change the annotation.

Spring Boot RestController Quiz

QUESTION:

HTTP Request methods

Since we are dealing with a web application, name any common http request methods you know or you have heard of. Separated by comma.

ANSWER:

Thanks for your response.
This is mine: PUT, GET, POST, DELETE, PATCH

Hello Servlet Heading

We have created a simple spring boot application with a controller. In the next few videos, we are going to dig a little deeper. And we are going to use Servlet, Filter and Listener class. All these classes are used by java backend server to receive requests, manipulate them and respond with responses.

Hello Servlet

Servlet is a technology/API/class that is used to create handle requests in web applications. Reside in server side, Spring Boot uses Servlet to receive requests from client side. There are two ways in Spring Boot to use Servlet Api:

  1. Use @ServletComponentScan annotation.
  2. Use @Bean annotation.

035ND C01 L02 A10 HELLO SERVLET

Hello Servlet Example Prep

  1. Create a servlet package under com.example.hello.

  2. Create a HelloServlet class under controller servlet.

  3. Add java code in the class

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name="helloServlet", urlPatterns ="/helloServlet")
public class HelloServlet extends HttpServlet{
   @Override
   protected void doGet(HttpServletRequest request, HttpServletResponse response) {
       System.out.println("Running Hello Servlet doGet method");
   }
}

Add the @ServletComponentScan under @SpringBootApplication in your helloWorldApplication.
Again, please make sure to use red bulb for missing imports.

Stop (Control + C) and Run the command below to start the application.

mvn spring-boot:run

When the application is ready, start a web browser and goto http://localhost:8080/helloServlet. You should see “Running Hello Servlet doGet method” printed in your console.

035ND C01 L02 A11 HELLO SERVLET EXAMPLE V2 (Post Launch) 1

If you look at the console, you can see the print message we added in our doGet method is printed here.

You may realize that we need to add @ServletComponentScan to make this application running. The @ServletComponentScan is making SpringBoot scan for @WebServlet annotation and it’s only performed when using an embedded web server such as Spring Boot. If you want to know more about ServletComponentScan, please take a look at its API doc:
https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/web/servlet/ServletComponentScan.html.

Filter

Filter is a component that is used to preprocessing and postprocessing requests. It can be used to validate, encrypt/decrypt, log requests. For instance, it can filter out request if it contains some invalid content, or ignore requests that do not contain required request parameter.

Let’s create a Filter under servlet.

  1. Create a HelloFilter class under servlet class
  2. Add the following code.
@WebFilter(filterName="helloFilter", urlPatterns="/helloServlet")
public class HelloFilter implements Filter {

   @Override
   public void doFilter(ServletRequest servletRequest,
                        ServletResponse servletResponse, FilterChain filterChain)
           throws IOException, ServletException {
       System.out.println("Executing doFilter method");
       filterChain.doFilter(servletRequest, servletResponse);
       System.out.println("Done executing doFilter method");
   }
}

035ND C01 L02 A12 HELLO FILTER

Listener for Servlet - instructions

In the previous videos, we have learned how to create Servlet and Filter. In this video, we are going to learn what Listener is and how to implement a simple Listener in Spring Boot.

Let’s create a Listener for Servlet

  1. Create a HelloListener class that implements ServletContextListener.
  2. Copy the code below to your class
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class HelloListener implements ServletContextListener {

   @Override
   public void contextDestroyed(ServletContextEvent servletContextEvent) {
       System.out.println("Servlet Context Destroyed");
   }

   @Override
   public void contextInitialized(ServletContextEvent servletContextEvent) {
       System.out.println("Servlet Context Initialized");
   }
}

Make sure to import necessary imports

035ND C01 L02 A13 HELLO LISTENER

Servlet with Bean - instructions

Let’s create servlet with bean. Bean is a very important concept in Spring. There are many definitions about what’s Bean. To make it short, Bean is an object that is used by Spring IoC container.

If you are interested in Bean or IoC please check the link below.

Bean: https://www.tutorialspoint.com/spring_boot/spring_boot_beans_and_dependency_injection.htm

Spring IoC: https://howtodoinjava.com/spring-core/different-spring-ioc-containers/

If you want to keep your existing code for future reference, you can stash your existing code, or copy it to another place. Switch to use bean is minimal here.

  1. Remove @ServletComponentScan annotation in Application class.
  2. Add the following method to Application class
/// Register Servlet.
@Bean
public ServletRegistrationBean getServletRegistrationBean() {
  ServletRegistrationBean servletBean = new ServletRegistrationBean(new HelloServlet());
  servletBean.addUrlMappings("/helloServlet");
  return servletBean;
}

/// Register Filter.
@Bean
public FilterRegistrationBean getFilterRegistrationBean() {
  FilterRegistrationBean filterBean = new FilterRegistrationBean(new HelloFilter());
  // Add filter path
  filterBean.addUrlPatterns("/helloServlet");
  return filterBean;
}

@Bean
public ServletListenerRegistrationBean<HelloListener> getServletListenerRegistrationBean() {
  ServletListenerRegistrationBean listenerBean =
        new ServletListenerRegistrationBean(new HelloListener());
  return listenerBean;
}

Make sure your imports are like below

import com.example.helloworld.servlet.HelloFilter;
import com.example.helloworld.servlet.HelloListener;
import com.example.helloworld.servlet.HelloServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

Run the application

Bean

If you are interested to know what bean and Ioc is? Here are the definitions:: https://www.baeldung.com/spring-bean.

If you take carefully into the console stack trace, you may notice we are using @Bean instead of @ServletComponentScan to create a Servlet, Filter and Listen.

035ND C01 L02 A14 HELLO BEAN

Spring Boot Servlet/Filter/Listener Quiz

If a web application has Servlet, Listener and Filter classes. Which of them will be instantiated first by the server?

SOLUTION: Listener

Spring Boot Servlet/Filter/Listener Quiz 2

Which object is used by the filters to get the next component invoked?

SOLUTION: FilterChain

Spring Boot Servlet/Filter/Listener Quiz 3

Which of the following objects can not be used by the listeners and servlets of an application for sharing information b/w them?

SOLUTION:
  • ServletRequest

Use Static resources

You may have noticed if you start your application and goto localhost:8080 direct, you will get an ugly error message. Let’s fix that by understanding how the static resource works in spring boot.

Let’s create an image folder under static folder. And copy any image you have on your computer to it. I am using a book logo.

Let’s create a html page with the following content.

Hello World
<img src="images/book.jpg" alt="Book" />

Let’s run the application and goto localhost:8080

035ND C01 L02 A15 STATIC RESOURCES

Spring Boot application for file upload - instructions

In this example, we are going to create a Spring Boot application for file upload. You can use the file upload application to upload your local file to your server (in this example, your local as well)

  1. Goto https://start.spring.io/ and enter artifact as spring-boot-file-upload
  2. Search for “Web” in dependency search and Select Spring Boot Web Starter
  3. Download, unzip and import as your intelliJ maven project.

View creation

Create an index.html under src/main/resources/static file. With a form and input and submit button. If you are not familiar with html, don’t worry about it right now. You can take a look it how it works here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file, feel free to your own code here.

<h3>File Upload</h3>
<form action="upload" method="post" enctype="multipart/form-data">
   Select file: <input type="file" name="attach"/><br />
   <input type="submit" value="Upload">
</form>

Create a controller
Create a controller directory and create a UploadController class inside

Map<String, Object> result = new HashMap<>();
/// Receive message
@RequestMapping("/uploadFile")
public Map<String, Object> upload(@RequestParam("attach")MultipartFile file) throws IOException {
   // File info
   System.out.println("File name = "  + file.getOriginalFilename());
   System.out.println("File type = " + file.getContentType());

   // Save to disk
   // file path example 1) Windows c:/, 3) Mac ~/Documents/
   String filePath = "~/Documents/";
   file.transferTo(new File(filePath + file.getOriginalFilename()));
   result.put("Success", true);
   return result;
}

Let’s run it.

Spring Boot File Upload

In case you have having issue with uploading big files. You can update the application.properties with the following statement

spring.http.multipart.maxFileSize=XXXMB

In case you want to try multiple files, you can update the configuration to

spring.http.multipart.maxRequestSize=XXXMB

035ND C01 L02 A16 SPRINGBOOT FILE UPLOAD

Lesson summary

035ND C01 L02 A18 LESSON RECAP

Spring Boot Upload file summary

How do you like Spring Boot so far? Let’s talk about some advanced spring boot components in our next lesson. See you around.